// 参考 test-code-1411-tomb.js 的登录/WS模板，聚合摊位全流程校验
const http = require('http');
const WebSocket = require('ws');

const CONFIG = {
    host: process.env.WS_HOST || 'localhost',
    port: parseInt(process.env.WS_PORT || process.env.HTTP_PORT || '3000', 10),
    mobile: process.env.TEST_USER_MOBILE || '17091279999',
    pwdHash: process.env.TEST_USER_PASSWORD_HASH || 'e10adc3949ba59abbe56e057f20f883e',
};

async function main() {
    console.log('\n🧪 开始【跳蚤市场摆摊】自测脚本...');
    const token = await loginOrRegister();
    console.log('🔐 登录成功，获取到 token');
    const ws = await connectWs(token);
    console.log('🔌 WebSocket 连接成功');
    await delay(200);
    console.log('👤 确保存在可用角色并选择...');
    await ensureCharacter(ws);
    console.log('✅ 角色已准备就绪');

    // 读取杂物背包，若无体力丹则跳过上架
    console.log('📦 查询杂物背包(1425) ...');
    try {
        const bag = await sendAndWait(ws, 1425, {});
        console.log('📦 杂物背包响应:', (JSON.stringify(bag) || '').slice(0, 400) + '...');
    } catch (e) {
        console.log('⚠️ 查询杂物背包失败，继续后续流程');
    }

    // 查看我的摊位
    console.log('🏪 查看我的摊位(1311) ...');
    let mine = await sendAndWait(ws, 1311, {});
    console.log('🏪 我的摊位响应:', JSON.stringify(mine));
    if (mine.code === 8) {
        // 首次访问即后端创建
        console.log('ℹ️ 首次访问，后端已创建摊位，重新获取...');
        mine = await sendAndWait(ws, 1311, {});
        console.log('🏪 二次查询我的摊位:', JSON.stringify(mine));
    }

    // 修改名字
    console.log('✏️ 修改摊位名称(1315) ...');
    try {
        const r = await sendAndWait(ws, 1315, { name: '我的摊名字' });
        console.log('✏️ 改名响应:', JSON.stringify(r));
    } catch {
        console.log('⚠️ 改名失败，继续');
    }

    // 预上架体力丹 1-4 个，单价 33333
    console.log('🧾 预上架(1325): 体力丹(id=82) x1 单价=33333 ...');
    try {
        const r = await sendAndWait(ws, 1325, { id: 82, pos: 0, count: 1, money: 33333 });
        console.log('🧾 预上架响应:', JSON.stringify(r));
    } catch {
        console.log('⚠️ 预上架失败(可能背包数量不足)，继续');
    }

    // 发布（普通）
    console.log('📣 发布摊位(1318): 普通发布 money=0 ...');
    try {
        const r = await sendAndWait(ws, 1318, { money: 0 });
        console.log('📣 发布响应:', JSON.stringify(r));
    } catch {
        console.log('⚠️ 发布失败，继续');
    }

    // 分类刷新
    console.log('📋 分类刷新(1264): type=1 pageNum=0 ...');
    try {
        const r = await sendAndWait(ws, 1264, { type: 1, pageNum: 0 });
        const preview = Array.isArray(r?.list) ? r.list.slice(0, 3) : r;
        console.log('📋 刷新响应(预览):', (JSON.stringify(preview) || '').slice(0, 400) + '...');
    } catch {
        console.log('⚠️ 分类刷新失败，继续');
    }

    // 查看我的出售记录
    const sid = mine?.data?.role_id || mine?.data?.roleId || 0;
    if (sid) {
        console.log('🧾 查看我的出售记录(1308) ...');
        try {
            const r = await sendAndWait(ws, 1308, { stallId: sid });
            console.log('🧾 出售记录响应:', JSON.stringify(r));
        } catch {
            console.log('⚠️ 出售记录查询失败');
        }
    }

    // 撤销
    console.log('↩️ 撤销摊位(1307) ...');
    try {
        const r = await sendAndWait(ws, 1307, {});
        console.log('↩️ 撤销响应:', JSON.stringify(r));
    } catch {
        console.log('⚠️ 撤销失败');
    }

    console.log('🎉 摆摊自测脚本执行完毕');

    try { ws.close(); } catch (_) { }
}

function loginOrRegister() {
    return new Promise((resolve, reject) => {
        const req = http.request({ hostname: CONFIG.host, port: CONFIG.port, path: '/user-service/user/login', method: 'POST', headers: { 'Content-Type': 'application/json' } }, (res) => {
            let data = ''; res.on('data', (c) => data += c); res.on('end', () => {
                try { const json = JSON.parse(data || '{}'); if (json.code === 0 && json.data?.accessToken) return resolve(json.data.accessToken); registerUser().then(() => loginOnly().then(resolve).catch(reject)).catch(() => loginOnly().then(resolve).catch(reject)); } catch { reject(new Error('登录响应解析失败')); }
            });
        }); req.on('error', reject); req.write(JSON.stringify({ mobile: CONFIG.mobile, pwd: CONFIG.pwdHash })); req.end();
    });
}
function loginOnly() {
    return new Promise((resolve, reject) => {
        const req = http.request({ hostname: CONFIG.host, port: CONFIG.port, path: '/user-service/user/login', method: 'POST', headers: { 'Content-Type': 'application/json' } }, (res) => {
            let data = ''; res.on('data', (c) => data += c); res.on('end', () => { try { const json = JSON.parse(data || '{}'); if (json.code === 0 && json.data?.accessToken) resolve(json.data.accessToken); else reject(new Error('登录失败')); } catch { reject(new Error('登录响应解析失败')); } });
        }); req.on('error', reject); req.write(JSON.stringify({ mobile: CONFIG.mobile, pwd: CONFIG.pwdHash })); req.end();
    });
}
function registerUser() {
    return new Promise((resolve) => {
        const req = http.request({ hostname: CONFIG.host, port: CONFIG.port, path: '/user-service/user/register', method: 'POST', headers: { 'Content-Type': 'application/json' } }, (res) => { res.on('data', () => { }); res.on('end', () => resolve(true)); }); req.on('error', () => resolve(true)); req.write(JSON.stringify({ mobile: CONFIG.mobile, pwd: CONFIG.pwdHash, captcha: '123456' })); req.end();
    });
}
function connectWs(token) { return new Promise((resolve, reject) => { const ws = new WebSocket(`ws://${CONFIG.host}:${CONFIG.port}/user-service/websocket?t=${token}`); ws.on('open', () => resolve(ws)); ws.on('error', reject); setTimeout(() => reject(new Error('WS连接超时')), 10000); }); }
async function ensureCharacter(ws) { const list = await waitAct(ws, 3, () => ws.send(JSON.stringify({ c: 3, d: null }))); const role = Array.isArray(list.roleList) && list.roleList[0]; if (!role) { await waitAct(ws, 5, () => ws.send(JSON.stringify({ c: 5, d: { name: '摊位测试', sex: 1, roleType: 1, headIndex: 2 } })), 15000); await delay(200); } const list2 = await waitAct(ws, 3, () => ws.send(JSON.stringify({ c: 3, d: null }))); const role2 = Array.isArray(list2.roleList) && list2.roleList[0]; if (!role2) throw new Error('无可用角色'); await waitAct(ws, 4, () => ws.send(JSON.stringify({ c: 4, d: { characterId: role2.id } }))); }
function sendAndWait(ws, actId, d) { return waitAct(ws, actId, () => ws.send(JSON.stringify({ c: actId, d: Object.keys(d || {}).length ? d : null }))); }
function waitAct(ws, actId, sendFn, timeoutMs = 10000) { return new Promise((resolve, reject) => { const handler = (raw) => { try { const msg = JSON.parse(raw.toString()); if (msg.act_id === actId) { ws.off('message', handler); clearTimeout(timer); resolve(msg); } } catch { } }; const timer = setTimeout(() => { ws.off('message', handler); reject(new Error(`等待 ${actId} 超时`)); }, timeoutMs); ws.on('message', handler); try { sendFn(); } catch (e) { ws.off('message', handler); clearTimeout(timer); reject(e); } }); }
function delay(ms) { return new Promise((r) => setTimeout(r, ms)); }

if (require.main === module) {
    main().catch((e) => { console.error('❌ 摆摊测试失败:', e.message); process.exit(1); });
} 